package feishuUtil

import (
	"encoding/json"
	"fmt"
	"go-api-template/service"
	"strings"
)

// SpreadSheetsI 数据文档接口
type SpreadSheetsI interface {
	InsertRows(tableId string, range_ string, data []interface{}) (InsertRowsResp, error)
	DeleteRows(tableId, sheetId string, startIndex int, endIndex int) (DeleteRowsResp, error) // 删除行列
}

type DeleteRowsResp struct {
	Code int `json:"code"`
	Data struct {
		DelCount       int    `json:"delCount"`
		MajorDimension string `json:"majorDimension"`
	} `json:"data"`
	Msg string `json:"msg"`
}

type InsertRowsResp struct {
	Code int `json:"code"`
	Data struct {
		DelCount       int    `json:"delCount"`
		MajorDimension string `json:"majorDimension"`
	} `json:"data"`
	Msg string `json:"msg"`
}

type OverlayRowsResp struct {
	Code int `json:"code"`
	Data struct {
		Revision         int    `json:"revision"`
		SpreadsheetToken string `json:"spreadsheetToken"`
		UpdatedCells     int    `json:"updatedCells"`
		UpdatedColumns   int    `json:"updatedColumns"`
		UpdatedRange     string `json:"updatedRange"`
		UpdatedRows      int    `json:"updatedRows"`
	} `json:"data"`
	Msg string `json:"msg"`
}

// DeleteRows 删除行
func (fc *FeishuClient) DeleteRows(tableId, sheetId string, startIndex int, endIndex int) (resp DeleteRowsResp, err error) {
	payload := strings.NewReader(fmt.Sprintf(`{"dimension": {"sheetId": "%s","majorDimension": "ROWS","startIndex": %d,"endIndex": %d}}`, sheetId, startIndex, endIndex))
	bs, err := fc.request("DELETE", fmt.Sprintf("/open-apis/sheets/v2/spreadsheets/%s/dimension_range", tableId), payload)
	if err != nil {
		return DeleteRowsResp{}, err
	}
	err = json.Unmarshal(bs, &resp)
	service.Log.Debug(string(bs))
	return
}

// InsertRows 插入行
func (fc *FeishuClient) InsertRows(tableId string, range_ string, data []interface{}) (resp InsertRowsResp, err error) {
	dataStr, err := json.Marshal(&data)
	payload := strings.NewReader(fmt.Sprintf(`{"valueRange": {"range": "%s","values": %s}}`, range_, dataStr))
	bs, err := fc.request("POST", fmt.Sprintf("/open-apis/sheets/v2/spreadsheets/%s/values_prepend", tableId), payload)
	if err != nil {
		return
	}
	err = json.Unmarshal(bs, &resp)
	service.Log.Debug(string(bs))
	return
}

// OverlayRows 覆盖写入行
func (fc *FeishuClient) OverlayRows(tableId string, range_ string, data []interface{}) (resp OverlayRowsResp, err error) {
	dataStr, err := json.Marshal(&data)
	payload := strings.NewReader(fmt.Sprintf(`{"valueRange": {"range": "%s","values": %s}}`, range_, dataStr))
	bs, err := fc.request("POST", fmt.Sprintf("/open-apis/sheets/v2/spreadsheets/%s/values", tableId), payload)
	if err != nil {
		return
	}
	err = json.Unmarshal(bs, &resp)
	service.Log.Debug(string(bs))
	return
}
